import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getChannels, getArticles, getArticle, editArticle, addArticle } from '../../store/actions/article';
import { Breadcrumb, Card, Input, Form, Select, Space, message, Button, Radio, Upload } from 'antd';
import { Link, useHistory, useParams,useLocation } from 'react-router-dom/cjs/react-router-dom.min';
// import { useParams} from "react-router-dom";
import Channel from '../../components/Channel/Channel'
import { PlusOutlined } from '@ant-design/icons';
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";

function Publish(props) {

    const [form] = Form.useForm();
    const history = useHistory();
    const [fileList, setFileList] = useState([]);
    const [type, setType] = useState(1);

    const onUploadChange = ({ fileList }) => {
        setFileList(fileList);
    }

    const onTypeChange = (e) => {
        setType(e.target.value);
        setFileList([]);
    }
    let [id,setid]=useState("")
    // 频道数据
    const channels = useSelector((state) => state.article.channels);
    const dispatch = useDispatch();
    const params = useParams();
console.log(params);
    useEffect(() => {
        const queryParams = new URLSearchParams(location.search);
        console.log(queryParams);
        setid(queryParams.get('id'));
       
        console.log(params.id);
        const setFormData = async () => {

            if (params.id) {
                const { title, cover, content, channel_id } = await dispatch(
                    getArticle(params.id)
                );
                console.log({ title, content, channel_id });
                form.setFieldsValue({ title, content, channel_id });
                setType(cover.type);
                setFileList(cover.images.map((item) => ({ url: item })));
            } else {
                setType(1)
                setFileList([])
                form.resetFields()
            }
        }
        setFormData();
    }, [dispatch, form, params]);
    const location = useLocation();
    // 提交表单
    const onFinish = async (values, draft = false) => {
        if (type !== fileList.length) {
            return message.warning('请按照选择的封面类型上传图片');
        }
        // 组织提交数据
        const data = {
            ...values,
            cover: {
                type,
                // 后台需要string类型
                images: fileList.map((item) => {
                    return item?.response?.data.url || item.url
                })
            }
        };
        if (params.id) {
            // 编辑
            data.id = params.id
            await dispatch(editArticle(data, draft))
            console.log(data, 'data');
        } else {
            await dispatch(addArticle(data, draft))
        }
        // await dispatch(getArticle(data));
        // 添加
        // await dispatch(addArticle(data))
        message.success('保存成功')
        history.push('/article');
    }
    // 存入草稿
    const saveDarft = async () => {
        try {
            const values = await form.validateFields()
            onFinish(values, true)
        } catch (e) { }
    }
    return (
        <div>
            <Card
                title={
                    <Breadcrumb>
                        <Breadcrumb.Item>
                            <Link to='/'>首页</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            <Link to='/article'>内容管理</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>{params.id ? '修改文章' : '发布文章'}</Breadcrumb.Item>
                    </Breadcrumb>
                }
            >
                <Form form={form} labelCol={{ span: 4 }} onFinish={onFinish}>
                    <Form.Item
                        label="文章标题:"
                        name="title"
                        rules={[{
                            required: true,
                            message: '请输入文章标题'
                        }]}
                    >
                        <Input placeholder='请输入文章标题' style={{ width: 400 }}></Input>
                    </Form.Item>
                    <Form.Item
                        label="所属频道"
                        name="channel_id"
                        rules={[{
                            required: true,
                            message: "请选择所属频道"
                        }]}
                    >
                        <Channel width={400} />
                    </Form.Item>

                    <Form.Item label="文章封面">
                        <Form.Item style={{ marginBottom: 0 }}>
                            <Radio.Group value={type} onChange={onTypeChange}>
                                <Radio value={1}>单图</Radio>
                                <Radio value={3}>三图</Radio>
                                <Radio value={0}>无图</Radio>
                            </Radio.Group>
                        </Form.Item>
                        {
                            type > 0 ? (
                                <div style={{ marginTop: 16 }}>
                                    <Upload
                                        name='image'
                                        listType='picture-card'
                                        action="http://geek.itheima.net/v1_0/upload"
                                        fileList={fileList}
                                        onPreview={() => { }}
                                        onChange={onUploadChange}
                                    >
                                        {fileList.length < type ? (
                                            <div>
                                                <PlusOutlined />
                                                <div style={{ marginTop: 8 }}>Upload</div>
                                            </div>
                                        ) : null}
                                    </Upload>
                                </div>
                            ) : null
                        }
                    </Form.Item>
                    <Form.Item
                        label="文章内容："
                        name="content"
                        initialValue=""
                        wrapperCol={{ span: 16 }}
                        rules={[{
                            required: true,
                            message: "请输入文章内容"
                        }]}
                    >
                        <ReactQuill placeholder="请输入文章内容" />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Space>
                            <Button type='primary' htmlType='submit'>{params.id ? '修改文章' : '发布文章'}</Button>
                            <Button onClick={saveDarft}>存入草稿</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    );
}

export default Publish;
